package com.cosmic.pizza.dao.Impl;

import com.cosmic.pizza.dao.FoodDao;
import com.cosmic.pizza.pojo.Food;
import com.cosmic.pizza.pojo.Food_Img;
import com.cosmic.pizza.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;


public class FoodDaoImpl implements FoodDao {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());
    @Override
    public List<Food> findByType(int start,int pageSize,int type) {
        String sql = "select * from tab_food where diff_id = ? limit ?,?";
        List<Food> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Food.class), type,start,pageSize);
        return list;
    }

    @Override
    public Food_Img findImg(Integer fid) {
        String sql = "select * from tab_food_img where fid = ?";
        List<Food_Img> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Food_Img.class), fid);
        return list!=null?list.get(0):null;
    }

    @Override
    public Food findByFid(Integer fid) {
        String sql = "select * from tab_food where fid = ?";
        List<Food> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Food.class), fid);
        return list!=null?list.get(0):null;
    }

    @Override
    public int countByType(int type) {
        String sql = "select count(*) from tab_food where diff_id = ? ";
        return jdbcTemplate.queryForObject(sql,Integer.class,type);
    }

    @Override
    public int countByFname(String fname) {
        StringBuilder _sql = new StringBuilder("select count(*)from tab_food where 1=1 ");
        if (fname!=null){
            _sql.append(" and fname like ? ");
            fname = "%"+fname+"%";
        }
        return jdbcTemplate.queryForObject(_sql.toString(),Integer.class,fname);
    }

    @Override
    public List<Food> findByFname(int start, int pageSize, String fname) {
        StringBuilder _sql = new StringBuilder("select * from tab_food where 1=1 ");
        if (fname!=null){
            _sql.append(" and fname like ? ");
            fname = "%"+fname+"%";
        }
        _sql.append("limit ?,?");
        return jdbcTemplate.query(_sql.toString(),new BeanPropertyRowMapper<>(Food.class),fname,start,pageSize);
    }

    @Override
    public void updateEval(int fid, String time, int evalsum, String sum) {
        String sql = "update tab_food set evalTime = ? , evalSum = ?,Sum = ? where fid = ?";
        jdbcTemplate.update(sql,time,evalsum,sum,fid);
    }
}
